//
//  VIPAllCollectionView.swift
//  GhostWorld
//
//  Created by Kam on 2018/9/27.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let contentCellIdentifier = "ContentCell"

struct VIPAllResultItem {
  enum ResultType: String {
    case group = "group"
    case album = "album"
  }
  
  var identifier: Int
  var name: String
  var type: ResultType
  var coverImageURL: URL
}

protocol VIPAllCollectionViewSelectionDelegate {
  func collectionView(_ collectionView: VIPAllCollectionView, didSelectItem item: VIPAllResultItem)
}

protocol VIPAllCollectionViewScrollDelegate {
  func vipAllCollectionViewDidScroll(_ scrollView: UIScrollView, didScroll: CGFloat)
}

class VIPAllCollectionView: UICollectionView {
  
  // MARK: - Private vars
  
  private var resultItems: [VIPAllResultItem]?
  
  // MARK: - Public methods
  
  var selectionDelegate: VIPAllCollectionViewSelectionDelegate?
  var scrollDelegate: VIPAllCollectionViewScrollDelegate?
  
  // MARK: - Lifecycle
  
  override func awakeFromNib() {
    super.awakeFromNib()
    
    dataSource = self
    delegate = self
  }
  
  // MARK: - Public methods
  
  func loadData(rootGroupIdentifier: Int) {
    API.shared.requestAPI (
      APIURLStrings.vipAllWithRootGroup(groupIdentifier: rootGroupIdentifier),
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        
        if let resultArray = json["results"].array, resultArray.count > 0 {
          self.resultItems = resultArray.map {
            VIPAllResultItem (
              identifier: $0["id"].intValue,
              name: $0["name"].stringValue,
              type: VIPAllResultItem.ResultType(rawValue: $0["type"].stringValue)!,
              coverImageURL: URL(string: "\(APIURLStrings.imagePrefix)/\($0["cover"])")!
            )
          }
        } else {
          self.resultItems = nil
        }
        self.reloadData()
        
    }) { (message, code) in
      loggingPrint("Load vip all failed: \(message)")
    }
  }
}

// MARK: - UICollectionViewDataSource

extension VIPAllCollectionView: UICollectionViewDataSource {
  
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
  }
  
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return resultItems?.count ?? 0
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCell
    
    if let resultItem = resultItems?[indexPath.row] {
      cell.prepare(item: resultItem)
    }
    return cell
  }
}

// MARK: - UICollectionViewDelegate

extension VIPAllCollectionView: UICollectionViewDelegate {
  
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let item = resultItems?[indexPath.row] {
      selectionDelegate?.collectionView(self, didSelectItem: item)
    }
  }
}

extension VIPAllCollectionView: UICollectionViewDelegateFlowLayout {
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (collectionView.width - 32) / 2 - 8
    let height = width * 185 / 143 - 30
    return CGSize(width: width, height: height)
  }
}

// MARK: - UIScrollViewDelegate

extension VIPAllCollectionView: UIScrollViewDelegate {
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    scrollDelegate?.vipAllCollectionViewDidScroll(self, didScroll: scrollView.contentOffset.y)
  }
}
